package com.sams.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.sams.entity.Authority;
import com.sams.entity.School;
import com.sams.entity.User;
import com.sams.mapper.SchoolMapper;
import com.sams.service.AuthorityService;
import com.sams.service.SchoolService;
import com.sams.service.UserService;
import com.sams.util.SamResult;

@RequestMapping("/user")
@Controller
public class UserController {
	
	@Autowired
	private UserService service;
	
	@Autowired
	private AuthorityService authorityService;
	
	@Autowired
	private SchoolService schoolService;
	
	@Autowired
	private SchoolMapper schoolMapper;
	
	public static HashMap<String, String> authMap= new HashMap<String,String>();

	@ResponseBody
	@RequestMapping("/login")
	public SamResult login(String username ,String password,
			HttpSession session) {
		//根据后台查询 
		SamResult result = service.login(username, password);
		if(result.getStatus()==200) {
		
			
			//根据用户角色 id  查询 它拥有的权限  并放入session中 
			User user = (User)result.getData();
			List<Authority> authList = authorityService.selectAthorByRoleId(user.getRoleid());
			for(Authority auth : authList) {
				authMap.put(auth.getUrl(), auth.getAuthorityName());
			}
			System.out.println("权限："+authMap);
			//缓存当前用户 所拥有的权限
			 session.setAttribute("userAuthMap",authMap );
			 session.setAttribute("user", result.getData());
			 session.setAttribute("userLoginDate", new Date());
			 
			 //查询该用户 对应的 所有学校 放入缓存中 
			 List<School> listAllSchool = new ArrayList<School>();
			 if(user.getRoleid()==1) {
				  // 说明是学校账户，查询它自己对应的学校
				 listAllSchool = schoolMapper.selectSchoolByXxid(user.getXxid());
				 
			 }else if(user.getRoleid()==2) {
				 //镇级别账号 ，查询它所管辖的学校
				  listAllSchool = schoolMapper.selectSchoolByUid(user.getId());
				 
			 }else {// 3， 4 说明是县级别用户  查询所有启动的学校
				 listAllSchool=schoolService.listAllSchool();
			 }
			
			 session.setAttribute("schoolList", listAllSchool);
		} 
		return result;
		 
	}
	
	@ResponseBody
	@RequestMapping("/getUser")
	public User getUserInfo(HttpSession session) {
		//获取session的用户
		User user = (User)session.getAttribute("user");
		return user;
	}
	
	@RequestMapping("/add")
	public String add(User user,Model model) {
		if(user.getRoleid()==1) {
			user.setUserlevel("校级别账户");
		}else if(user.getRoleid()==2) {
			user.setUserlevel("镇级别账户");
		}else if(user.getRoleid()==3) {
			user.setUserlevel("县级别账户");
		}else if(user.getRoleid()==4) {
			user.setUserlevel("后台管理员账户");
		}else {
			model.addAttribute("error", "账户级别不能为空");
			return "error";
		}
		int count = service.add(user);
		return "forward:/user/list";
	}
	
	@RequestMapping("/list")
	public String list(Integer currentPage,String usercode,Model model) {
		if(currentPage==null || currentPage==0) {
			currentPage=1;
		}
		PageInfo<User> pageInfo = service.listByPage(currentPage,usercode);
		 model.addAttribute("pageInfo", pageInfo);
		 model.addAttribute("usercode", usercode);
		 return "user";
	}
	
	@RequestMapping("/delete")
	public String delele(Integer uid) {
		int count = service.delete(uid);
		return "forward:/user/list";
	}
 
	@RequestMapping("/toUpdatePwd")
	public String toUpdatePwd(HttpServletRequest request,Model model) {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		
		return "updatePwd";
	}
	/**
	 * 修改密码
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/updatePwd")
	public String updatePwd(Integer id,String newpassword,
			String newrepassword,Model model,HttpServletResponse response) throws IOException {
		//验证 两次密码是否一致
		if(!newpassword.equals(newrepassword)) {
			model.addAttribute("error", "两次密码不一致，请重新修改");
			return "error";
		}
	   boolean flag = service.updatePwd(id,newpassword);
	    if(flag) {
	    	response.setCharacterEncoding("UTF-8");
	    	response.setContentType("text/html;charset=UTF-8");
	    	 PrintWriter out = response.getWriter();
	    	 out.print("<script>alert('修改成功，请重新登录');parent.window.location='../login.html'</script>");
	    	 return null;
	    }else {
	    	model.addAttribute("error", "密码修改失败。");
			return "error";
	    }
	    
	}
	
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,Model model,HttpServletResponse response) throws IOException {
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}else {
			request.getSession().removeAttribute("user");
			response.setCharacterEncoding("UTF-8");
	    	response.setContentType("text/html;charset=UTF-8");
	    	 PrintWriter out = response.getWriter();
			out.print("<script>parent.window.location='../login.html'</script>");
	    	 return null;
		}
		
	 
	}
	
}
